// Copyright (c) 2024 IndustrialTBB Framework
// Complete usage example

#include "itbb/itbb.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <iostream>

using namespace std::chrono_literals;

int main() {
    try {
        std::cout << "=== IndustrialTBB Framework Complete Example ===" << std::endl;
        
        // 1. 配置框架
        itbb::FrameworkInitConfig config;
        config.max_threads = 8;
        config.enable_performance_monitoring = true;
        config.enable_device_auto_recovery = true;
        config.monitoring_interval = 500ms;
        
        // 2. 创建并初始化框架
        itbb::IndustrialTBBFramework framework(config);
        
        if (!framework.Initialize()) {
            std::cerr << "Failed to initialize framework!" << std::endl;
            return 1;
        }
        
        std::cout << "Framework initialized successfully!" << std::endl;
        
        // 3. 创建性能指标
        auto task_counter = framework.CreateCounter("tasks.executed");
        auto response_timer = framework.CreateTimer("device.response_time");
        auto cpu_gauge = framework.CreateGauge("system.cpu_usage");
        
        // 4. 创建并注册ADwin设备
        bool device_created = framework.CreateAndRegisterAdwinDevice(
            "ADwin-Lab-01", "192.168.1.100", 6543);
        
        if (device_created) {
            std::cout << "ADwin device created and registered!" << std::endl;
        }
        
        // 5. 添加周期性任务
        framework.AddPeriodicTask("DataCollection", 100ms, [&]() {
            // 模拟数据采集
            auto timer_scope = response_timer->CreateScope();
            
            auto* device = framework.GetDevice("ADwin-Lab-01");
            if (device) {
                // 执行设备操作
                framework.ExecuteDeviceOperation("ADwin-Lab-01", 
                    [](itbb::ITbbIndustrialDevice* dev) {
                        // 模拟读取操作
                        std::this_thread::sleep_for(1ms);
                        return true;
                    });
            }
            
            task_counter->Increment();
        });
        
        // 6. 添加系统监控任务
        framework.AddPeriodicTask("SystemMonitoring", 1s, [&]() {
            // 模拟CPU使用率
            static double cpu_usage = 0.0;
            cpu_usage = 20.0 + 30.0 * std::sin(
                std::chrono::steady_clock::now().time_since_epoch().count() / 1e9);
            cpu_gauge->SetValue(cpu_usage);
            
            // 输出系统信息
            auto system_info = framework.GetSystemInfo();
            std::cout << "Uptime: " << 
                std::chrono::duration_cast<std::chrono::seconds>(system_info.uptime).count() 
                << "s, Devices: " << system_info.healthy_devices << "/" 
                << system_info.total_devices << std::endl;
        });
        
        // 7. 提交一些异步任务
        for (int i = 0; i < 10; ++i) {
            framework.SubmitTask([i, &task_counter]() mutable {
                std::this_thread::sleep_for(10ms);
                std::cout << "Async task " << i << " completed" << std::endl;
                task_counter->Increment();
            }, itbb::TaskPriority::kNormal);
        }
        
        // 8. 连接所有设备
        if (framework.ConnectAllDevices()) {
            std::cout << "All devices connected successfully!" << std::endl;
        }
        
        // 9. 配置动态调整示例
        framework.SetConfig("monitoring.enabled", true);
        framework.SetConfig("framework.max_threads", 12.0);
        
        // 10. 运行一段时间后导出指标
        std::this_thread::sleep_for(5s);
        
        std::cout << "\n=== Performance Metrics ===" << std::endl;
        auto metrics_json = framework.ExportMetrics("json");
        std::cout << metrics_json << std::endl;
        
        // 11. 健康检查
        auto health = framework.GetHealthStatus();
        std::cout << "=== Health Status ===" << std::endl;
        std::cout << "Overall Healthy: " << (health.overall_healthy ? "Yes" : "No") << std::endl;
        std::cout << "Health Score: " << health.health_score << std::endl;
        
        for (const auto& component : health.component_health) {
            std::cout << "  " << component.component_name << ": " 
                     << (component.healthy ? "OK" : "FAIL") 
                     << " - " << component.status_message << std::endl;
        }
        
        // 12. 等待所有任务完成
        framework.WaitForAllTasks();
        
        std::cout << "\n=== Final Statistics ===" << std::endl;
        std::cout << "Tasks executed: " << task_counter->GetValue() << std::endl;
        
        auto timer_stats = response_timer->GetStatistics();
        std::cout << "Average response time: " << timer_stats.avg_value << "ms" << std::endl;
        
        // 13. 优雅关闭
        framework.Shutdown();
        std::cout << "Framework shutdown completed." << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}
